import {EditOutlined, EyeOutlined, FlagOutlined, SearchOutlined, UndoOutlined} from '@ant-design/icons';
import { Button, message, Form, DatePicker, Modal, Row, Col, Input, Tag, Tooltip } from 'antd';
import locale from "antd/es/date-picker/locale/zh_CN";
import 'moment/locale/zh-cn'

import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import '@/assets/css/index.less';
import ProForm, { ProFormText } from '@ant-design/pro-form';
import { getVoteByVoteId, getVoteResultList, publishVote } from '@/services/voteApi';
import { formatDateDayjs } from '@/utils/formatDate';
import { ProFormRadio } from '@ant-design/pro-components';
import { useModel } from 'umi';
import {LocalFormat} from "@/utils/localHelper";
const formLayout = {
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 10,
  },
};
const voteTemplate: React.FC = () => {
  const [voteForm] = Form.useForm();
  const [search_form] = Form.useForm();
  const actionRef = useRef<ActionType>();
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(40);
  const [dataArray, setDataArray] = useState([]);
  const [pageSize, setPageSize] = useState(10);
  const [pagination, setPagination] = useState({
    current: page,
    pageSize: pageSize,
    position: ['bottomRight'],
    size: 'small',
    showSizeChanger: true,
    total: total,
  });
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  const [modalVisible, setModalVisible] = useState(false);
  const [voteOptionList, setVoteOptionList] = useState([]);
  const handleTableChange = (pagination: any) => {
    setPage(pagination.current);
    setPageSize(pagination.pageSize);
    setPagination({ ...pagination });
  };
  useEffect(() => {
    queryData();
  }, [page, pageSize]);

  const queryData = async () => {
    let values = search_form.getFieldsValue();
    const params = {
      roleId: currentUser.roleId,
      page: page,
      pageSize: pageSize,
      ...values,
    };
    const msg = await getVoteResultList(params);
    setDataArray(msg.data.list);
    setPagination({ ...pagination, total: msg.data.total });
  };

  const getVoteInfoByID = async (record) => {
    const voteInfo = await getVoteByVoteId({
      voteId: record.id,
    });
    formatDateDayjs([voteInfo.data.vote], 'startTime', 'YYYY-MM-DD');
    formatDateDayjs([voteInfo.data.vote], 'endTime', 'YYYY-MM-DD');
    const obj = { ...voteInfo.data.vote };

    voteForm.setFieldsValue(obj);
    setVoteOptionList(voteInfo.data.voteOptionList);
    setModalVisible(true);
  };

  const _initSearchForm = () => {
    return (
      <div className="ant-pro-table-search ant-pro-table-search-query-filter">
        <Form
          form={search_form}
          className="ant-form ant-form-horizontal ant-pro-form-query-filter"
          layout="inline"
        >
          <Row style={{ width: '100%' }}>
            <Col span={4}>
              <Form.Item label="标题" name="title">
                <Input placeholder="请输入标题" />
              </Form.Item>
            </Col>

            <Col span={10}></Col>

            <Col
              span={10}
              className="basic-search-form-submit-btn"
              style={{ display: 'flex', justifyContent: 'flex-end' }}
            >
              <Button
                onClick={() => {
                  search_form.resetFields();
                  queryData();
                }}
              >                <UndoOutlined />

                重置
              </Button>
              &nbsp;&nbsp;
              <Button type="primary" htmlType="submit" onClick={() => queryData()}>
                <SearchOutlined />
                查询
              </Button>
            </Col>
          </Row>
        </Form>
      </div>
    );
  };

  const columns: ProColumns[] = [
    {
      title: '标题',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'title',
      render: (_, record) => {
        return (
          <Tooltip title={record.description} color="#108ee9" placement="rightBottom">
            {record.title}
          </Tooltip>
        );
      },
    },
    {
      title: '状态',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'publish',
      render: (_, record) => {
        if (record.publish == false) {
          return (
            <Tag color="blue" key="wfb">
              未发布
            </Tag>
          );
        } else if (record.publish == true) {
          return (
            <Tag color="green" key="yfb">
              已发布
            </Tag>
          );
        }
      },
    },
    {
      title: '发布人',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'createdBy',
    },
    {
      title: '开始时间',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'startTime',
    },
    {
      title: '结束时间',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'endTime',
    },

    {
      title: '操作',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'id',
      render: (_, record) => [
        <a
          key="edit"
          onClick={() => {
            getVoteInfoByID(record);
          }}
        >

          <Button type={'primary'} shape={'round'} icon={<EyeOutlined />}>
            查看
          </Button>
        </a>,
      ],
    },
  ];
  return (
    <PageContainer>
      {_initSearchForm()}
      <ProTable
        search={false}
        options={false}
        actionRef={actionRef}
        rowKey={'id'}
        tableStyle={{ textAlign: 'center' }}
        onChange={handleTableChange}
        pagination={pagination}
        dataSource={dataArray}
        columns={columns}
      ></ProTable>

      <Modal
        title={'投票'}
        width="600px"
        destroyOnClose
        open={modalVisible}
        onCancel={() => {
          setModalVisible(false);
          voteForm.resetFields();
        }}
        footer={[
          <Button
            key="close"
            onClick={() => {
              setModalVisible(false);
            }}
          >
            关闭
          </Button>,
        ]}
      >
        <ProForm form={voteForm} layout="horizontal" {...formLayout} submitter={false}>
          <ProFormText
            width="md"
            name="title"
            label="投票标题"
            disabled
            rules={[
              {
                required: true,
                message: '请输入标题',
              },
            ]}
          />
          <Form.Item label="开始时间" name="startTime">
            <DatePicker locale={locale} disabled />
          </Form.Item>
          <Form.Item label="结束时间" name="endTime">
            <DatePicker locale={locale} disabled />
          </Form.Item>
          <Form.Item label="投票结果">
            <ul>
              {voteOptionList.map((item, index) => {
                return (
                  <li key={index}>
                    {item.name} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;票数：{item.num}
                  </li>
                );
              })}
            </ul>
          </Form.Item>
        </ProForm>
      </Modal>
    </PageContainer>
  );
};
export default voteTemplate;
